import { getMenus } from '@/api/system/user'
import Layout from '@/layout/index'
import { constantRoutes } from '@/router'

const permissions = {
  state: {
    routes: []
  },
  mutations: {
    SET_ROUTES: (state, route) => {
      state.routes = route
    }
  },
  actions: {
    // 查询路由信息
    getRoutes({ commit }) {
      return new Promise(resolve => {
        getMenus().then(res => {
          const routesData = JSON.parse(JSON.stringify(res.data))
          const newRoutestData = filterRouter(routesData)
          newRoutestData.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', constantRoutes.concat(newRoutestData))
          resolve(newRoutestData)
        })
      })
    }
  }
}

// 过滤路由
function filterRouter(routes) {
  return routes.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterRouter(route.children)
    }
    return true
  })
}
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permissions
